package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.CMUtil
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.kh.dh.HttpClient
import cn.com.kh.getProperty
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @projectName: ngsapitask-v3
 * @package: cn.com* @className: chatproxy* @author: LiJT* @description: 项目Token相关统一管理接口* @date: 2022-09-29 13:21
 * @version: 1.0
 */

public class apiCMAPIProxy implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiCMAPIProxy.class);
    private static String log_Prefix = "自动同步CM模板-";

    private static String CM_ProductToken = "b4b49728-9eda-4f10-980e-da21ac4372b7";
    private static String CM_AccountID = "154d3c2e-472c-40df-a0e9-597647da4069";
    private static String CM_ChannelRequestId = "f47f65e1-52dd-4607-818a-67ec91c658ff";

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            log.warn(log_Prefix + "API被非法IP调用-Request Not Allow!");
            return "Request Not Allow!";
        }

        // 获取数据源
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        CM_ProductToken = KHDBConfig.getParamConfig(eliteBean, "CM_ProductToken");
        CM_AccountID = KHDBConfig.getParamConfig(eliteBean, "CM_AccountID");
        CM_ChannelRequestId = KHDBConfig.getParamConfig(eliteBean, "CM_ChannelRequestId");

        String Syncpram = "";

        String getMethod = request.getMethod();
        if (getMethod.equals("GET")) {
            Syncpram = request.getQueryString();
            log.info("接收调用GET参数信息：" + Syncpram);
        } else if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                Syncpram += line;
            }

            log.info("接收调用POST报文信息：" + System.getProperty("line.separator") + Syncpram);
        }

        JSONObject resultBody = new JSONObject();
        resultBody.put("code", "1");
        resultBody.put("msg", "Call successful");

        try {
            // 解析请求报文
            JSONObject callJson = JSONObject.fromObject(Syncpram);

            String call_type = callJson.getString("call_type");
            String call_flag = callJson.has("call_flag") ? callJson.getString("call_flag") : "";
            String call_url = callJson.getString("call_url");
            JSONObject call_data = callJson.getJSONObject("call_data");
            log.debug(log_Prefix + "代理API基础信息:call_type：" + call_type + " call_flag：" + call_flag + " call_url：" + call_url + " call_data：" + call_data.toString());

            // 处理头文件
            Map<String, String> headParams = new HashMap<String, String>();
            headParams.put("Content-Type", "application/json;charset=utf-8");
            headParams.put("X-CM-PRODUCTTOKEN", CM_ProductToken);

            // 发起调用
            String resultInfo = "";

            if (call_type == "DELETE") {
                resultInfo = HttpClient.httpDelete(call_url, headParams, "utf-8");
                log.debug(log_Prefix + "代理API DELETE结果:" + resultInfo);
                resultBody.put("data", resultInfo);

            } else {
                if (call_type == "PUT") {
                    resultInfo = HttpClient.httpPutRaw(call_url, call_data.toString(), headParams, "utf-8");
                    log.debug(log_Prefix + "代理API PUT结果:" + resultInfo);
                } else {
                    resultInfo = Util.doHttpPostUseHead(call_url, call_data.toString(), "UTF-8", 120000, 0, headParams);
                    log.debug(log_Prefix + "代理API POST结果:" + resultInfo);
                }

                // 处理返回信息
                try {
                    JSONObject resultJson = JSONObject.fromObject(resultInfo);
                    if (resultJson.containsKey("id")) {
                        resultBody.put("data", resultJson);

                        if (call_flag == "CM_UpdateTemplate") {
                            String Templates_ID = CMUtil.saveTemplat(eliteBean, jt, resultJson);
                            // 处理返回信息
                            JSONObject resultObj = JSONObject.fromObject(resultJson);
                            JSONObject languagesJson = resultObj.getJSONObject("languages");

                            // 循环入库
                            for (Object str : languagesJson.keySet()) {
                                String languageType = str;
                                JSONObject tempJson = languagesJson.getJSONObject(languageType);
                                CMUtil.saveTemplatLang(eliteBean, jt, tempJson, Templates_ID, languageType);
                            }
                        }
                    } else {
                        resultBody.put("code", "0");
                        resultBody.put("msg", "Call failed");
                        resultBody.put("data", resultJson);
                    }
                } catch (Exception e) {
                    log.error("代理机器人接口检查是否需要返回转人工异常", e);
                    // 失败返回
                    resultBody.put("code", "-1");
                    resultBody.put("msg", "调用结果解析异常：" + e.getMessage());

                }
            }

        } catch (Exception e) {
            log.error("接口处理异常", e);
            // 失败返回
            resultBody.put("code", "-1");
            resultBody.put("msg", "调用代理异常：" + e.getMessage());

        }

        log.debug("Proxy处理完成返回结果:" + resultBody.toString());

        return resultBody.toString();
    }

}
